//
//  UpdateHouseViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/23.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "UpdateHouseViewController.h"
#import "TZImagePickerController.h"

#import "FirstView.h"
#import "SecondView.h"
#import "ThreeView.h"
#import "FourView.h"

@interface UpdateHouseViewController ()<TZImagePickerControllerDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>{
    UIScrollView *sclView;
}

@property (nonatomic, strong) NSMutableDictionary *resultDic;

@property (nonatomic, strong) FirstView *oneView;

@property (nonatomic, strong) SecondView *twoView;

@property (nonatomic, strong) ThreeView *threeView;

@property (nonatomic, strong) FourView *fourView;

@property (nonatomic, strong) UIAlertController *sheet;

@property (nonatomic, strong) NSMutableArray *oneDataImageArray;

@end

@implementation UpdateHouseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setBGColor];
    [self showNav:@"修改"];
    
    [self loadUI];
    
    [self loadData];
}

- (void)loadUI{
    sclView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
    sclView.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    sclView.contentSize = CGSizeMake(ScreenWidth, 1523);
    [self.view addSubview:sclView];
    
    self.oneView = [[[NSBundle mainBundle] loadNibNamed:@"FirstView" owner:nil options:nil] lastObject];
    self.oneView.frame = CGRectMake(0, 0, ScreenWidth, 200);
    [sclView addSubview:self.oneView];
    
    
    self.twoView = [[[NSBundle mainBundle] loadNibNamed:@"SecondView" owner:nil options:nil] lastObject];
    self.twoView.frame = CGRectMake(0, self.oneView.frame.size.height+self.oneView.frame.origin.y+10, ScreenWidth, 300);
    [sclView addSubview:self.twoView];
    
    self.threeView = [[[NSBundle mainBundle] loadNibNamed:@"ThreeView" owner:nil options:nil] lastObject];
    self.threeView.frame = CGRectMake(0, self.twoView.frame.size.height+self.twoView.frame.origin.y+10, ScreenWidth, 293);
    [sclView addSubview:self.threeView];
    //500+293+534+50+40
    self.fourView = [[[NSBundle mainBundle] loadNibNamed:@"FourView" owner:nil options:nil] lastObject];
    self.fourView.frame = CGRectMake(0, self.threeView.frame.size.height+self.threeView.frame.origin.y+10, ScreenWidth, 640);
    [sclView addSubview:self.fourView];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setBackgroundColor:HexColorInt32_t(FD1142)];
    btn.frame = CGRectMake(0, self.fourView.frame.size.height+self.fourView.frame.origin.y+10, ScreenWidth, 50.0);
    [btn setTitle:@"确定修改" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(editEvent:) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sclView addSubview:btn];
    
    __block typeof(self) bself = self;
    self.fourView.updateHeightAction = ^(NSInteger arrCount) {
        CGFloat height = (arrCount - 1) * 323;
        bself.fourView.frame = CGRectMake(0, self.threeView.frame.size.height+self.threeView.frame.origin.y+10, ScreenWidth, 640 + height);
        sclView.contentSize = CGSizeMake(ScreenWidth, 1523 + height);
        btn.frame = CGRectMake(0, self.fourView.frame.size.height + self.fourView.frame.origin.y + 10, ScreenWidth, 50.0);
    };
    
    self.oneView.addImageActionButton = ^(UIButton *sender) {
        if (self.oneDataImageArray.count < 6) {
            [bself presentViewController:bself.sheet animated:YES completion:nil];
        }
    };
    
    self.sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        BOOL ishave = [self doesCameraSupportTakingPhotos];
        if (ishave == YES) {
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.delegate = self;
            [self presentViewController:picker animated:YES completion:nil];
        }else{
            [LICGToast showWithText:@"相机不可用" bottomOffset:20 duration:5];
        }
    }];
    
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        BOOL ishave = [self isPhotoLibraryAvailable];
        if (ishave == YES) {
            TZImagePickerController *imagePC=[[TZImagePickerController alloc]initWithMaxImagesCount:6 delegate:self];
            [imagePC setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *imagarr, NSArray *array, BOOL bl) {
                UIImage *selimage = [imagarr firstObject];
                
                [self.oneView.poimage setHidden:YES];
                [self.oneView.zhulabel setHidden:YES];
                [self.oneView.updateLabel setHidden:YES];
                if (self.oneView.bgImageView.image == nil) {
                    [self.oneView.bgImageView setImage:selimage];
                }
                //async -- 并发队列
                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                for (UIImage *itemImg in imagarr) {
                    dispatch_async(queue, ^{
                        [self uploadImage:itemImg];
                        NSLog(@"-----上传图片1---%@", [NSThread currentThread]);
                    });
                }
                
                
            }];
            [self presentViewController:imagePC animated:YES completion:nil];
        }else{
            [LICGToast showWithText:@"相册不可用" bottomOffset:20 duration:5];
        }
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [self.sheet addAction:cancelAction];
    [self.sheet addAction:cameraAction];
    [self.sheet addAction:albumAction];
    
}

#pragma mark ====UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [self.oneView.poimage setHidden:YES];
    [self.oneView.zhulabel setHidden:YES];
    [self.oneView.updateLabel setHidden:YES];
    if (self.oneView.bgImageView.image == nil) {
        [self.oneView.bgImageView setImage:image];
    }
    [self uploadImage:image];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)uploadImage:(UIImage *)image{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:@"pic.png" forKey:@"pic"];
    [parmas setObject:@"name" forKey:@"name"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@/App/Norm/upload",urlHead];
    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:data name:@"pic" fileName:fileName mimeType:@"image/png"];
        [formData appendPartWithFileData:data name:@"name" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *op = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSLog(@"dic:%@",op);
        NSInteger error =[[op objectForKey:@"error"] integerValue];
        if (error == 200) {
            NSString *imageString = [op objectForKey:@"result"];
            NSLog(@"imgUrl1:%@",imageString);
            [self.oneDataImageArray addObject:imageString];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

- (void)loadData{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    
    NSString *rentid = [self.editDic objectForKey:@"id"];
    
    [parmas setValue:token forKey:@"verifiToken"];
    [parmas setValue:[user objectForKey:@"userid"] forKey:@"userid"];
    [parmas setValue:rentid forKey:@"id"];
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Rentout/xgrent",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"房源详情res:%@",responseObject);
        NSInteger state = [[responseObject objectForKey:@"error"] integerValue];
        NSString *msg = [responseObject objectForKey:@"mssage"];
        NSDictionary *reDic = [responseObject objectForKey:@"result"];
        if (state == 200 && [reDic isKindOfClass:[NSDictionary class]]) {
            self.resultDic = [reDic mutableCopy];
            [self bindData];
            [SVProgressHUD dismiss];
        }else{
            [SVProgressHUD showErrorWithStatus:msg];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
}

- (void)bindData{
    NSString *picString = [self.resultDic objectForKey:@"pic"];
    NSArray *picArray = [picString componentsSeparatedByString:@"|"];
    self.oneDataImageArray = [picArray mutableCopy];
    NSString *picImageUrlString = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[picArray firstObject]];
    [self.oneView.bgImageView sd_setImageWithURL:[NSURL URLWithString:picImageUrlString]];
    [self.oneView.poimage setHidden:YES];
    [self.oneView.zhulabel setHidden:YES];
    [self.oneView.updateLabel setHidden:YES];
    
    
    [self.twoView.biaoTitle setText:[self.resultDic objectForKey:@"title"]];
    [self.twoView.zuText setText:[self.resultDic objectForKey:@"mnthly"]];
    [self.twoView.payLabel setText:[self.resultDic objectForKey:@"payment"]];
    [self.twoView.tingLabel setText:[self.resultDic objectForKey:@"room"]];
    [self.twoView.mianText setText:[self.resultDic objectForKey:@"area"]];
    [self.twoView.zuTypeLabel setText:[self.resultDic objectForKey:@"mode"]];
   
    [self.threeView.zhuangText setText:[self.resultDic objectForKey:@"rnovation"]];
    [self.threeView.caoText setText:[self.resultDic objectForKey:@"toward"]];
    [self.threeView.louText setText:[self.resultDic objectForKey:@"floor"]];
    [self.threeView.yongText setText:[self.resultDic objectForKey:@"use"]];
    [self.threeView.typeText setText:[self.resultDic objectForKey:@"type"]];
    [self.threeView.yearsText setText:[self.resultDic objectForKey:@"bilttime"]];
    [self.threeView.quText setText:[self.resultDic objectForKey:@"community"]];
    self.threeView.baiduInfo.name = [self.resultDic objectForKey:@"community"];
    double latitude = [[self.resultDic objectForKey:@"latitude"] doubleValue];
    double longitude = [[self.resultDic objectForKey:@"longitude"] doubleValue];
    self.threeView.baiduInfo.pt = CLLocationCoordinate2DMake(latitude, longitude);
    
    
    [self.fourView.gaishuLabel setText:[self.resultDic objectForKey:@"text"]];
    
    NSArray *miaoArray = [self.resultDic objectForKey:@"teristic"];
    [self.fourView setFourData:miaoArray];
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}


- (NSMutableDictionary *)resultDic{
    if (!_resultDic) {
        _resultDic = [[NSMutableDictionary alloc]init];
    }
    return _resultDic;
}

- (NSMutableArray *)oneDataImageArray{
    if (!_oneDataImageArray) {
        _oneDataImageArray = [[NSMutableArray alloc]init];
    }
    return _oneDataImageArray;
}

- (void)editEvent:(UIButton *)sender{
    NSString *topImageString = [self.oneDataImageArray componentsJoinedByString:@"|"];
    NSString *titleString = self.twoView.biaoTitle.text;
    NSString *zuPriceString = self.twoView.zuText.text;
    NSString *payString = self.twoView.payLabel.text;
    NSString *roomString = self.twoView.tingLabel.text;
    NSString *mianString = self.twoView.mianText.text;
    NSString *zuTypeString = self.twoView.zuTypeLabel.text;
    
    NSString *zhuangString = self.threeView.zhuangText.text;
    NSString *caoString = self.threeView.caoText.text;
    NSString *cengString = self.threeView.louText.text;
    NSString *yongString = self.threeView.yongText.text;
    NSString *huTypeString = self.threeView.typeText.text;
    NSString *cTime = self.threeView.yearsText.text;
    
    
    NSString *gaiString = self.fourView.gaishuLabel.text;
    NSString *tuwenSTtring = [self.fourView getImageAndTitleDataArray];
    
    if ([self isNullOrEmpty:topImageString]) {
        [LICGToast showWithText:@"请上传图片" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:titleString]) {
        [LICGToast showWithText:@"请填写标题" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:zuPriceString]) {
        [LICGToast showWithText:@"请填写租金" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:payString]) {
        [LICGToast showWithText:@"请选择付款方式" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:roomString]) {
        [LICGToast showWithText:@"请选择厅室" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:mianString]) {
        [LICGToast showWithText:@"请填写面积" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:zhuangString]) {
        [LICGToast showWithText:@"请选择装修" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:caoString]) {
        [LICGToast showWithText:@"请选择朝向" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:cengString]) {
        [LICGToast showWithText:@"请选择楼层" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:yongString]) {
        [LICGToast showWithText:@"请选择用途" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:huTypeString]) {
        [LICGToast showWithText:@"请选择户型" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:cTime]) {
        [LICGToast showWithText:@"请选择建于时间" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:gaiString]) {
        [LICGToast showWithText:@"请填写房源概述" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:self.threeView.quText.text]) {
        [LICGToast showWithText:@"请选择小区" bottomOffset:20 duration:5];
        return;
    }
    
    if ([self isNullOrEmpty:tuwenSTtring]) {
        [LICGToast showWithText:@"请添加图文说明" bottomOffset:20 duration:5];
        return;
    }
    
    
    
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parmas = [[NSMutableDictionary alloc]init];
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    
    NSString *fid = [self.resultDic objectForKey:@"id"];
    
    [parmas setValue:token forKey:@"verifiToken"];
    [parmas setValue:[user objectForKey:@"userid"] forKey:@"userid"];
    [parmas setValue:fid forKey:@"id"];
    [parmas setValue:topImageString forKey:@"pic"];
    [parmas setValue:titleString forKey:@"title"];
    [parmas setValue:zuPriceString forKey:@"mnthly"];
    [parmas setValue:payString forKey:@"payment"];
    [parmas setValue:roomString forKey:@"room"];
    [parmas setValue:mianString forKey:@"area"];
    [parmas setValue:zuTypeString forKey:@"mode"];
    [parmas setValue:zhuangString forKey:@"rnovation"];
    [parmas setValue:caoString forKey:@"toward"];
    [parmas setValue:cengString forKey:@"floor"];
    [parmas setValue:yongString forKey:@"use"];
    [parmas setValue:huTypeString forKey:@"type"];
    [parmas setValue:cTime forKey:@"bilttime"];
    [parmas setValue:gaiString forKey:@"text"];
    [parmas setValue:self.threeView.baiduInfo.name forKey:@"community"];
    [parmas setValue:@(self.threeView.baiduInfo.pt.longitude) forKey:@"longitude"];
    [parmas setValue:@(self.threeView.baiduInfo.pt.latitude) forKey:@"latitude"];
    [parmas setValue:tuwenSTtring forKey:@"teristic"];
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Rentout/properties",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"修改房源res:%@",responseObject);
        NSInteger state = [[responseObject objectForKey:@"error"] integerValue];
        NSString *msg = [responseObject objectForKey:@"mssage"];
        if (state == 200) {
            [SVProgressHUD showSuccessWithStatus:msg];
            [self.delegate reloadDataList];
        }else{
            [SVProgressHUD showErrorWithStatus:msg];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
